import base64
import hashlib
import json
import requests
from Crypto.Cipher import AES


def push_server_chan(tz_logs):
    if sc_key is None or sc_key == "":
        print("跳过推送")
        return
    params = {
        'text': "网易云音乐自动脚本",
        'desp': tz_logs
    }
    server_url = "https://sc.ftqq.com/" + sc_key + ".send"
    response = requests.session().post(server_url, data=params)
    if response.status_code == 200:
        print("推送成功")


def encrypt(key, text):
    cryptor = AES.new(key.encode('utf8'), AES.MODE_CBC, b'0102030405060708')
    length = 16
    count = len(text.encode('utf-8'))
    if count % length != 0:
        add = length - (count % length)
    else:
        add = 16
    pad = chr(add)
    text1 = text + (pad * add)
    ciphertext = cryptor.encrypt(text1.encode('utf8'))
    cryptedStr = str(base64.b64encode(ciphertext), encoding='utf-8')
    return cryptedStr


def md5(str):
    hl = hashlib.md5()
    hl.update(str.encode(encoding='utf-8'))
    return hl.hexdigest()


def protect(text):
    return {"params": encrypt('TA3YiYCfY2dDJQgg', encrypt('0CoJUm6Qyw8W8jud', text)),
            "encSecKey": "84ca47bca10bad09a6b04c5c927ef077d9b9f1e37098aa3eac6ea70eb59df0aa28b691b7e75e4f1f9831754919ea784c8f74fbfadf2898b0be17849fd656060162857830e241aba44991601f137624094c114ea8d17bce815b0cd4e5b8e2fbaba978c6d1d14dc3d1faf852bdd28818031ccdaaa13a6018e1024e2aae98844210"}

# class Web_c():
#
#     def __init__(self):



def do_checkin(login_user, logon_pwd, tz_logs):
    s = requests.Session()
    header = {}
    url = "https://music.163.com/weapi/login/cellphone"
    url2 = "https://music.163.com/weapi/point/dailyTask"
    url3 = "https://music.163.com/weapi/v1/discovery/recommend/resource"
    logindata = {
        "phone": login_user,
        "country_code": "86",
        "password": md5(logon_pwd),
        "rememberLogin": "true",
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/84.0.4147.89 Safari/537.36',
        "Referer": "http://music.163.com/",
        "Accept-Encoding": "gzip, deflate",
    }
    headers2 = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36',
        "Referer": "http://music.163.com/",
        "Accept-Encoding": "gzip, deflate",
        "Cookie": "os=pc; osver=Microsoft-Windows-10-Professional-build-10586-64bit; appver=2.0.3.131777; channel=netease; __remember_me=true;"
    }

    res = s.post(url=url, data=protect(json.dumps(logindata)), headers=headers2)
    temp_cookie = res.cookies
    r_object = json.loads(res.text)
    if r_object['code'] == 200:
        print("登录成功！")
        tz_logs += f'账号{logindata["phone"]}登录成功！\n\n'
    else:
        print(f"登录失败！请检查密码是否正确！{r_object['code']}")
        tz_logs += f'账号{logindata["phone"]}登录失败！请检查密码是否正确！\n\n'
        return tz_logs + str(r_object['code'])

    res = s.post(url=url2, data=protect('{"type":0}'), headers=headers)
    r_object = json.loads(res.text)
    if r_object['code'] != 200 and r_object['code'] != -2:
        print(f"签到时发生错误：{r_object['msg']}")
    else:
        if r_object['code'] == 200:
            print(f"签到成功，经验{r_object['point']}")
            tz_logs += f"签到成功，经验{r_object['point']}\n\n"
        else:
            print("重复签到")
            tz_logs += "重复签到\n\n"

    res = s.post(url=url3,
                 data=protect('{"csrf_token":"' + requests.utils.dict_from_cookiejar(temp_cookie)['__csrf'] + '"}'),
                 headers=headers)
    r_object = json.loads(res.text, strict=False)
    for x in r_object['recommend']:
        url = 'https://music.163.com/weapi/v3/playlist/detail?csrf_token=' + \
              requests.utils.dict_from_cookiejar(temp_cookie)[
                  '__csrf']
        data = {
            'id': x['id'],
            'n': 1000,
            'csrf_token': requests.utils.dict_from_cookiejar(temp_cookie)['__csrf'],
        }
        res = s.post(url, protect(json.dumps(data)), headers=headers)
        r_object = json.loads(res.text, strict=False)
        buffer = []
        count = 0
        for j in r_object['playlist']['trackIds']:
            data2 = {"action": "play", "json": {}}
            data2["json"]["download"] = 0
            data2["json"]["end"] = "playend"
            data2["json"]["id"] = j["id"]
            data2["json"]["sourceId"] = ""
            data2["json"]["time"] = "240"
            data2["json"]["type"] = "song"
            data2["json"]["wifi"] = 0
            buffer.append(data2)
            count += 1
            if count >= 310:
                break
        if count >= 310:
            break
    url = "http://music.163.com/weapi/feedback/weblog"
    post_data = {
        "logs": json.dumps(buffer)
    }
    res = s.post(url, protect(json.dumps(post_data)))
    r_object = json.loads(res.text, strict=False)
    if r_object['code'] == 200:
        print(f"刷单成功！共{count}首")
        tz_logs += f"刷单成功！共{count}首\n\n"
        return tz_logs
    else:
        print(f"发生错误：{r_object['code']}{r_object['message']}")
        tz_logs += f"发生错误：{r_object['code']}{r_object['message']}\n\n" 
        return tz_logs + str(r_object['code'])


if __name__ == '__main__':
    tz_logs = ""
    login_user_list = input().split("#")
    login_pwd_list = input().split("#")
    sc_key = input()
    if len(login_user_list) != len(login_pwd_list):
        print("账号和密码个数不对应")
        tz_logs += "账号和密码个数不对应\n\n"
    else:
        print(f"共有{len(login_user_list)}个账号，即将开始签到")
        tz_logs += f"共有{len(login_user_list)}个账号，即将开始签到\n\n"
        for login_user, login_pwd in zip(login_user_list, login_pwd_list):
            try:
                tz_logs = do_checkin(login_user, login_pwd, tz_logs)
            except BaseException as e:
                tz_logs += f'程序出现异常{e}\n'
        tz_logs += "执行完成"
    push_server_chan(tz_logs)
    exit()